package com.cisdi.analysis.web.controller;

import com.cisdi.analysis.core.dto.AnalysisDataDTO;
import com.cisdi.analysis.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;

/**
 * 上传文件控制器
 * @author liujunnan
 * @date 2018/5/23
 */
@RestController
@RequestMapping("/file")
public class FileController extends BaseController {

    @Autowired
    private FileService fileService;

    /**
     * 文件上传，同时导入文件到数据库
     * @param file 文件对象
     * @return 文件本地连接和远程连接和原先名字
     */
    @PostMapping("/upload")
    public Map upload(@RequestParam("file") MultipartFile file) throws Exception {
        return fileService.upload(file);
    }

    /**
     * 删除指定行
     * @param number    给定行数
     * @return 删除后的文件地址
     * @throws Exception
     */
    @DeleteMapping("/row")
    public String deleteRow(Integer number) throws Exception {
        return fileService.deleteRow(number, localPath);
    }

    /**
     * 删除指定列数
     * @param number    给定列数
     * @return 删除后的文件地址
     * @throws IOException
     */
    @DeleteMapping("/list")
    public String deleteList(Integer number) throws Exception {
        return fileService.deleteList(number, localPath);
    }

    /**
     * 修改行
     * @param number          第几行
     * @param analysisDataDTO 修改后的数据
     * @return 修改后的路径
     * @throws Exception
     */
    @PutMapping("/row")
    public String updateRow(Integer number, @RequestBody AnalysisDataDTO analysisDataDTO) throws Exception {
        return fileService.updateRow(number, localPath, analysisDataDTO);
    }

    /**
     * 断点下载
     * @param response
     * @param request
     * @return
     */
    @GetMapping("/download")
    public String download(HttpServletResponse response, HttpServletRequest request) {
        InputStream inputStream = null;
        ServletOutputStream out = null;
        try {
            File file = new File(localPath);
            int fSize = Integer.parseInt(String.valueOf(file.length()));
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/x-download");
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Content-Length", String.valueOf(fSize));
            response.setHeader("Content-Disposition", "attachment;fileName=" + "download.csv");
            inputStream = new FileInputStream(localPath);
            long pos = 0;
            if (null != request.getHeader("Range")) {
                // 断点续传
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                try {
                    pos = Long.parseLong(request.getHeader("Range").replaceAll(
                            "bytes=", "").replaceAll("-", ""));
                } catch (NumberFormatException e) {
                    pos = 0;
                }
            }
            out = response.getOutputStream();
            String contentRange = new StringBuffer("bytes ").append(pos + "").append(
                    "-").append((fSize - 1) + "").append("/").append(fSize + "").toString();
            response.setHeader("Content-Range", contentRange);
            inputStream.skip(pos);
            byte[] buffer = new byte[1024 * 10];
            int length = 0;
            while ((length = inputStream.read(buffer, 0, buffer.length)) != -1) {
                out.write(buffer, 0, length);
                Thread.sleep(100);
            }
        } catch (Exception e) {
            logger.error("软件下载异常：" + e);
        } finally {
            try {
                if (null != out) {
                    out.flush();
                }
                if (null != out) {
                    out.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "OK";
    }
}
